local m_BuildingFerry1Info = GameInfo.Buildings['BUILDING_FERRY1']
local m_Ferrytime
local GAME_SPEED = GameConfiguration.GetGameSpeedType()
local GAME_SPEED_MULTIPLIER = GameInfo.GameSpeeds[GAME_SPEED] and GameInfo.GameSpeeds[GAME_SPEED].CostMultiplier / 100 or 1
local FERRY_LEADER_TYPE = 'LEADER_FERRY'


function OnCityAddedToMap(playerID,cityID,cityX,cityY)
    if PlayerConfigurations[playerID]:GetLeaderTypeName() == FERRY_LEADER_TYPE then
	--print('this is 1')
        local pPlayer = Players[playerID]	
		local pCity = pPlayer:GetCities():FindID(cityID)
        pCity:GetBuildQueue():CreateBuilding(m_BuildingFerry1Info.Index)
    	local Ferrycity = Game:GetProperty('Ferry_city')
		    if Ferrycity == nil then
			    Ferrycity = {}
		    end
		table.insert(Ferrycity, {
			        CityID = cityID,
			        Littimes = 1,
	        })
		--print('this is 2')
		Game:SetProperty('Ferry_city', Ferrycity)
	end
end

function OnCityConquered(newPlayerID, oldPlayerID, newCityID, iCityX, iCityY)
    if PlayerConfigurations[newPlayerID]:GetLeaderTypeName() == FERRY_LEADER_TYPE then
        local pPlayer = Players[newPlayerID]	
		local pCity = pPlayer:GetCities():FindID(newCityID)
		local destroyCities = Game:GetProperty('destroy_city')
		if destroyCities == nil then
			destroyCities = {}
		end
		table.insert(destroyCities, {
			NewPlayerID = newPlayerID,
			X = iCityX,
			Y = iCityY,
		})
		Game:SetProperty('destroy_city', destroyCities)
        pCity:GetBuildQueue():CreateBuilding(m_BuildingFerry1Info.Index)
	end
end


function allocateInteger(M, N)
    local result = {}
    local quotient = math.floor(M / N)
    local remainder = M % N

    for i = 1, N do
        result[i] = quotient
    end

    for i = 1, remainder do
        local index = Game.GetRandNum(N) + 1 
        result[index] = result[index] + 1 
    end

    return result
end

function OnTurnBegin()
	for _, i in ipairs(PlayerManager.GetWasEverAliveMajorIDs()) do
		if PlayerConfigurations[i] and PlayerConfigurations[i]:GetLeaderTypeName() == FERRY_LEADER_TYPE then
			local pPlayer = Players[i]
			local turn:number = Game.GetCurrentGameTurn();
            if (turn >= m_Ferrytime*GAME_SPEED_MULTIPLIER ) then
			    local pPlayerCities = pPlayer:GetCities();
            	m_Ferrytime = m_Ferrytime + 10
            	Game:SetProperty('cl_Ferrytime', m_Ferrytime)
                for _, pCity in pPlayerCities:Members() do
                    pCity:ChangePopulation(0)
                    --local neighborPlot = Map.GetNeighborPlots(pCity:GetX(), pCity:GetY(), 3)
                    --for i, adjPlot in ipairs(neighborPlot) do
                    --   print(i, adjPlot:GetIndex())
                    --	if (not adjPlot:IsOwned()) then
                    --		print('success2')	
                    --		if ExposedMembers.KTM and ExposedMembers.KTM.GetMorePlot and ExposedMembers.KTM.GetMorePlot(pPlayer:GetID(),pCity:GetID(),adjPlot:GetIndex()) then
                    --        break
                    --        end
                    --    end
                    --end
                    local Ferrycity = Game:GetProperty('Ferry_city')
		                for _, PlotcityID in ipairs(Ferrycity) do
		    	            if (PlotcityID.CityID == pCity:GetID()) then 
		    	            	PlotcityID.Littimes =  PlotcityID.Littimes + 1
		    	            	if (PlotcityID.Littimes == 1) then
		    	            	pCity:AttachModifierByID('MODIFIER_FERRY_GET_CHEAP_TILES')
		    	            	end	
		    	            end
		    	        end
		    	    Game:SetProperty('Ferry_city', Ferrycity)
                end
            end
		end
	end

    local destroyCities = Game:GetProperty('destroy_city')
	if destroyCities then
		for _, destroyCity in ipairs(destroyCities) do
			local pop:number = 0
            if PlayerConfigurations[destroyCity.NewPlayerID]:GetLeaderTypeName() == FERRY_LEADER_TYPE then
				local pCity = CityManager.GetCityAt(destroyCity.X, destroyCity.Y)
				if pCity then
					pop = pCity:GetPopulation()
					CityManager.DestroyCity(pCity)
				end
			end
			local pPlayer = Players[destroyCity.NewPlayerID]
            local citynum:number = 0
		    local pPlayerCities = pPlayer:GetCities();
		    for _ , allCity in pPlayerCities:Members() do
		        citynum = citynum + 1
		    end
		    local allocation = allocateInteger(pop, citynum)
		    for i, part in ipairs(allocation) do
		        for n , aCity in pPlayerCities:Members() do
		            if (n == i) then 
		            aCity:ChangePopulation(part)
		            break
		            end
		        end
		    end
        end 
    end
    Game:SetProperty('destroy_city', {})
end

local FREE_CIVIC_KEY = 'HD_FREE_CIVIC';
GameEvents.HD_FreeCivicSwitch.Add(function (playerId, civicId)
	local player = Players[playerId];
	local remains = player:GetProperty(FREE_CIVIC_KEY) or 0;
	local playerCulture = player:GetCulture();
-- 	player:SetProperty(FREE_CIVIC_KEY, remains - 1);
	playerCulture:SetCulturalProgress(civicId, playerCulture:GetCultureCost(civicId));
end);
GameEvents.BuildingConstructed.Add(function (playerId,cityId,buildingId)
		local player = Players[playerId];
		local remains = player:GetProperty(FREE_CIVIC_KEY) or 0;
		local FREE_CIVIC_FERRY = 'BUILDING_FERRY3';
		local FERRY_3_BUILDINGS = player:GetProperty(FREE_CIVIC_FERRY) or 0;
		if FERRY_3_BUILDINGS > 0 then return end --1 free civic
		if (buildingId == GameInfo.Buildings['BUILDING_FERRY3'].Index) then
					-- print('something has been built');
					-- print(buildingId);
			player:SetProperty(FREE_CIVIC_KEY, remains + 1);
			player:SetProperty(FREE_CIVIC_FERRY, FERRY_3_BUILDINGS + 1);
					-- print('FERRY_3_BUILDINGS',FERRY_3_BUILDINGS);
    	end
end);


function OnCityMadePurchase(playerID,cityID,plotX,plotY,purchaseType,objectType)
    if (PlayerConfigurations[playerID]:GetLeaderTypeName() == FERRY_LEADER_TYPE )then
        if purchaseType ~= EventSubTypes.PLOT then
		return
	    end
	    local Ferrycity = Game:GetProperty('Ferry_city')
		for _, PlotcityID in ipairs(Ferrycity) do
		    if (PlotcityID.CityID == cityID) then 
		    	if (PlotcityID.Littimes == 0) then
		    	return
		    	end  
		    	PlotcityID.Littimes = PlotcityID.Littimes - 1
		    	if (PlotcityID.Littimes == 0) then
		    	local pPlayer = Players[playerID]	
		    	local pCity = pPlayer:GetCities():FindID(cityID)
		    	pCity:AttachModifierByID('MODIFIER_FERRY_GET_EXPENSIVE_TILES')
		    	end	
		    end
	    end
		Game:SetProperty('Ferry_city', Ferrycity)
    end
end

function Initialize()
	GameEvents.CityBuilt.Add(OnCityAddedToMap)
	GameEvents.CityConquered.Add(OnCityConquered)
	Events.CityMadePurchase.Add(OnCityMadePurchase)
    Events.TurnBegin.Add(OnTurnBegin)

    local Ferrytime = Game:GetProperty('cl_Ferrytime');
	if Ferrytime == nil then
	   Ferrytime = 9 + Game.GetCurrentGameTurn();
	   Game:SetProperty('cl_Ferrytime', Ferrytime)
	end
	m_Ferrytime = Ferrytime

end
Initialize();